layui.use(['jquery', 'layer', 'table', 'form', 'tree'], function() {
	let $ = layui.$;
	let layer = layui.layer;
	let table = layui.table;
	let form = layui.form;
	let tree = layui.tree;

	//查询
	$("#role-search-form .search-btn").click(function() {
		reloadData();
		return false;
	});


	//数据列表
	if (base.isInRole('role_page')) {
		loadTable()
	}

	function loadTable() {
		let loadIndex = layer.msg('加载中...', {
			icon: 16,
			shade: 0.1
		});
		table.render({
			elem: '#role-table',
			url: base.path + '/rolePage',
			where: {
				token: base.getToken()
			},
			method: 'post',
			done: function(res, curr, count) {
				layer.close(loadIndex);
			},
			cols: [
				[{
						field: 'id',
						title: '序号',
						templet: function(res) {
							return res.LAY_INDEX;
						}
					},
					{
						field: 'name',
						title: '角色名称'
					},
					{
						field: 'userCnt',
						title: '用户数量'
					},
					{
						field: 'permissionCnt',
						title: '权限数量'
					},
					{
						field: 'state',
						title: '角色状态',
						templet: function(res) {
							return res.state == 1 ? "<span style='color:#1E9FFF'>有效</span>" : "<span style='color:#FF5722'>无效</span>";
						}
					},
					{
						field: 'system',
						title: '系统角色',
						templet: function(res) {
							return res.system == 1 ? "<span style='color:#1E9FFF'>是</span>" : "<span style='color:#FF5722'>否</span>";
						}
					},
					{
						title: '操作',
						fixed: 'right',
						align: 'center',
						width: 200,
						templet: function(res) {
							let html = '';
							if (res.system == 0) {
								if (base.isInRole('role_update')) {
									html += "<button lay-event='edit' class='layui-btn layui-btn-sm layui-bg-blue'>编辑</button>"
								}
								if (base.isInRole('permission_list')) {
									html += "<button lay-event='permission-list' class='layui-btn layui-btn-sm layui-bg-red'>分配权限</button>";
								}
							}
							return html;
						}
					}
				]
			],
			limits: [5, 10, 20],
			page: true
		});
	}

	//重新加载
	function reloadData() {
		let loadIndex = layer.msg('加载中...', {
			icon: 16,
			shade: 0.1
		});
		table.reload('role-table', {
			page: {
				curr: 1
			}, //从第一页开始
			where: {
				name: $("#role-search-form [name='name']").val(),
				state: $("#role-search-form [name='state']").val(),
				token: base.getToken()
			},
			done: function(res, curr, count) {
				layer.close(loadIndex);
			},
		});
	}

	//添加角色
	if (!base.isInRole('role_add')) {
		$('#role-add').hide();
	}
	let roleAddLayer;
	$('#role-add').click(function() {
		roleAddLayer = layer.open({
			type: 1,
			title: '添加角色',
			area: ['400px'],
			skin: 'layer-ext-skin',
			content: $('#role-add-dialog'),
			btn: ['提交', '关闭'],
			success: function(layero, index) {
				$("#role-add-form").find("input[name='token']").val(base.getToken());
			},
			yes: function(index, layero) {
				$('#role-add-btn').click(); //模拟点击 校验不能为空
			}
		});
	});

	//监听form表单提交
	form.on('submit(role-add-form)', function(data) {
		base.ajax({
			url: '/roleAdd',
			data: $('#role-add-form').serialize(),
			success: function(res) {
				if (res.code == 0) {
					layer.alert('添加成功', function(index) {
						layer.close(index);
						layer.close(roleAddLayer);
						table.reload('role-table');
						$('#role-add-form')[0].reset();
					});

				} else {
					layer.alert(res.msg);
				}
			}
		});
		return false;
	});

	//监听工具栏事件
	table.on('tool(role-table)', function(obj) {
		let d = obj.data;
		switch (obj.event) {
			case 'edit':
				$("#role-edit-form").find("input[name='id']").val(d.id);
				$("#role-edit-form").find("input[name='name']").val(d.name);
				$("#role-edit-form").find("select[name='state']").val(d.state);
				$("#role-edit-form").find("input[name='token']").val(base.getToken());
				layui.form.render('select'); //刷新select下拉框
				edit();
				break;
			case 'permission-list':
				permissionList(d.id);
				break;
		}
	});

	//编辑角色
	function edit() {
		layer.open({
			type: 1,
			title: '编辑角色',
			area: ['400px'],
			skin: 'layer-ext-skin',
			content: $('#role-edit-dialog'),
			btn: ['提交', '关闭'],
			yes: function(index, layero) {
				base.ajax({
					url: '/roleUpdate',
					data: $('#role-edit-form').serialize(),
					success: function(res) {
						if (res.code == 0) {
							layer.alert('修改成功', function(index2) {
								layer.close(index2);
								layer.close(index);
								table.reload('role-table');
							});

						} else {
							layer.alert(res.msg);
						}
					}
				});
			}
		});
	}

	//分配权限
	function permissionList(roleId) {
		layer.open({
			type: 1,
			title: '分配权限',
			area: ['420px', '500px'],
			content: $('#role-permission-tree-dialog'),
			btn: ['提交', '关闭'],
			yes: function(index, layero) {
				// 获取所有已选中节点
				let checkedNodes = tree.getChecked('role-permission-tree-id');
				let checkedIds = [];
				getCheckedIds(checkedNodes, checkedIds);
				base.ajax({
					url: '/rolePermission/add',
					data: {
						roleId: roleId,
						permissionIds: checkedIds.toString(),
						token: base.getToken()
					},
					success: function(res) {
						if (res.code == 0) {
							layer.alert('设置成功', function(index2) {
								layer.close(index2);
								layer.close(index);
								table.reload('role-table');
							});
						} else {
							layer.alert(res.msg);
						}
					}
				});
			},
			success: function() {
				base.ajax({
					url: '/rolePermissionList',
					data: {
						roleId: roleId,
						token: base.getToken()
					},
					success: function(res) {
						if (res.code == 0) {
							tree.render({
								elem: '#role-permission-tree',
								data: res.data,
								showCheckbox: true,
								id: 'role-permission-tree-id'
							});
						} else {
							layer.alert(res.msg);
						}
					}
				});
			}
		});
	}

	//递归获取选中的权限ID
	function getCheckedIds(checkedNodes, checkedIds) {
		for (let i in checkedNodes) {
			let o = checkedNodes[i];
			checkedIds.push(o.id);
			if (o.children != undefined && o.children.length > 0) {
				getCheckedIds(o.children, checkedIds);
			}
		}
	}

});
